package com.boilermaker.lotterysystem.controller;

import com.boilermaker.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.boilermaker.lotterysystem.common.exception.ControllerException;
import com.boilermaker.lotterysystem.common.pojo.CommonResult;
import com.boilermaker.lotterysystem.common.utils.JacksonUtil;
import com.boilermaker.lotterysystem.controller.param.CreateActivityParam;
import com.boilermaker.lotterysystem.controller.param.PageParam;
import com.boilermaker.lotterysystem.controller.vo.ActivityDetailVO;
import com.boilermaker.lotterysystem.controller.vo.CreateActivityVO;
import com.boilermaker.lotterysystem.controller.vo.ActivityListVO;
import com.boilermaker.lotterysystem.service.ActivityService;
import com.boilermaker.lotterysystem.service.dto.ActivityDTO;
import com.boilermaker.lotterysystem.service.dto.ActivityDetailDTO;
import com.boilermaker.lotterysystem.service.dto.CreateActivityDTO;
import com.boilermaker.lotterysystem.service.dto.PageListDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class ActivityController {

    /**
     * 活动模块注入
     */
    @Autowired
    private ActivityService activityService;

    /**
     * 创建活动，保存活动信息
     *
     * @param param
     * @return
     */
    @RequestMapping("/activity/create")
    public CommonResult<CreateActivityVO> createActivity(
            @Validated @RequestBody CreateActivityParam param) {

        log.info("createActivity CreateActivityParam : {}", JacksonUtil.writeValueAsString(param));

        CreateActivityDTO dto = activityService.createActivity(param);

        return CommonResult.success(convertCreateActivityDtoToVo(dto));
    }

    /**
     * 获取活动列表，支持翻页功能
     */
    @RequestMapping("/activity/find-list")
    public CommonResult<ActivityListVO> findActivityList(PageParam param) {
        log.info("findActivityList PageParam:{}", JacksonUtil.writeValueAsString(param));

        PageListDTO<ActivityDTO> pageListDTO = activityService.findActivityList(param);

        return CommonResult.success(convertFindActivityListDtoToVo(pageListDTO));
    }

    /**
     * 根据活动 ID 获取活动详细信息
     *
     * @param activityId
     * @return
     */
    @RequestMapping("/activity-detail/find")
    public CommonResult<ActivityDetailVO> getActivityDetail(Long activityId) {
        log.info("getActivityDetail activityId : {}", activityId);

        ActivityDetailDTO activityDetailDTO = activityService.getActivityDetail(activityId);

        return CommonResult.success(convertGetActivityDetailDtoToVo(activityDetailDTO));
    }

    /**
     * 将 DTO 转换为 VO。DTO 仅用于传输业务数据，而 VO 站在前端需求角度封装数据。
     *
     * @param dto
     * @return
     */
    private ActivityDetailVO convertGetActivityDetailDtoToVo(ActivityDetailDTO dto) {

        if (dto == null) {
            throw new ControllerException(ControllerErrorCodeConstants.GET_ACTIVITY_DETAIL_ERROR);
        }

        ActivityDetailVO vo = new ActivityDetailVO();
        vo.setActivityId(dto.getActivityId());
        vo.setActivityName(dto.getActivityName());
        vo.setDescription(dto.getDesc());
        vo.setValid(dto.valid());

        vo.setPrizes(
                dto.getPrizeDTOList().stream()
                        // 以一等奖、二等奖、三等奖的顺序返回结果
                        .sorted(Comparator.comparingInt(prizeDTO -> prizeDTO.getTiers().getCode()))
                        .map(prizeDTO -> {
                            ActivityDetailVO.Prize prize = new ActivityDetailVO.Prize();

                            prize.setPrizeId(prizeDTO.getPrizeId());
                            prize.setName(prizeDTO.getName());
                            prize.setImageUrl(prizeDTO.getImageUrl());
                            prize.setPrice(prizeDTO.getPrice());
                            prize.setDescription(prizeDTO.getDescription());
                            prize.setPrizeTierName(prizeDTO.getTiers().getMessage());
                            prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                            prize.setValid(prizeDTO.valid());

                            return prize;
                        }).collect(Collectors.toList())
        );

        vo.setUsers(
                dto.getUserDTOList().stream()
                        .map(userDTO -> {
                            ActivityDetailVO.User user = new ActivityDetailVO.User();

                            user.setUserId(userDTO.getUserId());
                            user.setUserName(userDTO.getUserName());
                            user.setValid(userDTO.valid());

                            return user;
                        }).collect(Collectors.toList())
        );
        return vo;
    }

    private ActivityListVO convertFindActivityListDtoToVo(PageListDTO<ActivityDTO> dto) {

        if (dto == null) {
            throw new ControllerException(ControllerErrorCodeConstants.FIND_ACTIVITY_LIST_ERROR);
        }

        ActivityListVO vo = new ActivityListVO();
        vo.setTotal(dto.getTotal());
        vo.setRecords(dto.getRecords()
                .stream()
                .map(activityDTO -> {
                    ActivityListVO.ActivityInfo activityInfo = new ActivityListVO.ActivityInfo();
                    activityInfo.setActivityId(activityDTO.getActivityId());
                    activityInfo.setActivityName(activityDTO.getActivityName());
                    activityInfo.setDescription(activityDTO.getDescription());
                    activityInfo.setValid(activityDTO.valid());
                    return activityInfo;
                }).collect(Collectors.toList())
        );
        return vo;
    }

    private CreateActivityVO convertCreateActivityDtoToVo(CreateActivityDTO dto) {

        if (dto == null) {
            throw new ControllerException(ControllerErrorCodeConstants.CREATE_ACTIVITY_ERROR);
        }

        CreateActivityVO vo = new CreateActivityVO();
        vo.setActivityId(dto.getActivityId());

        return vo;
    }
}
